//  Created by 莫瑞权 on 2022/6/2.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit
import SDWebImage

import TalkFunBarrageRenderer
import AFNetworking

public class TF1vnMainViewController: UIViewController,TF_CourseDownLoadDetailDelegate,UITextViewDelegate,TFLotteryViewControllerDelegate,TFMyLotteryViewControllerDelegate, TF_SignInDelegate {
 
    //课程密钥
     @objc public var access_token:String = ""
     @objc public var userID: String = ""
    //6是大班互动模式
    //5小班模式
    //3大班模式
//    @objc public
    var modetype:String = ""
    //0：非小班
    //1：双人，
    //2：1V6 模式，
    //3：1V16模式

//    @objc public
    var smallType:String = ""
    
    
    //横竖屏   true: 横屏  false:竖屏
    var isOrientationLandscape:Bool = false
    
     @objc var drawPower:Bool = false  //是否打开涂鸦权限
     //课前聊天
     @objc var mod_beforeclass_live:Bool = false
     //课后聊天
     @objc var mod_afterclass_live:Bool = false
     
     @objc public let scoreView = TFScore1vN()
     
     @objc public var isScore:Bool = false //记录有没有开启评分
    
    @objc public var TF_isStatusBarHidden:Bool = false
    
    
     @objc public let talkfunSDK = TalkfunSDKLive.shareInstance()
    
    //网络网络状态
    @objc var alertInvite = TFAlertView()
    @objc public let qskQuestionsView = TFQskQuestions1to16()//提问回答
    @objc public let promptTool = TFFenPromptTool()
    @objc public let imageManage = SDWebImageManager()
    //设置线路
//    @objc public let setButtonView = TFSetButtonView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    @objc public let setButtonView = TFSetButtonView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    //弹幕 sdk
    @objc public let barrageRender = TalkFunBulletView()
     // 全屏view
    @objc public let fullView = TFFullView()
    @objc public let chatArea = TF1to16ChatArea()
    //3分屏幕自带的chatArea
    @objc public let chatThreeArea = TF1to16ChatArea()

    //投票
    @objc public let votingArea = TF1to16VotingArea()
    @objc public let keyboardTool = TFkeyboardTool()//键盘工具
     var prize_name:String = ""
    //导航栏
    @objc public let navigationBar = TF1to16NavigationBarTools()
    @objc public let awardView = TFAwardView() //自己的奖励
    @objc public let other = TFLine1Vn()//其它配置(前后摄像与弹幕)
    //签到
    @objc public let signInView = TF_SignIn()
//     @objc public let signInView1 = TF_SignIn()//签到
    //通知  (超出屏幕宽度会跑马灯式显示)
    @objc public  let marquee = TFMarquee()
    // 提问发送倒计时
    @objc public var qa_sendTimer:Timer?
    // 聊天发送倒计时
    @objc public var chat_sendTimer:Timer?
    //提问间隔
    @objc public var qa_t:NSInteger = 0
    //聊天间隔
    @objc public var chat_t:NSInteger = 0
    //聊天限制
    @objc public var chatFrequentlyClick:Bool = false
    //问答限制
    @objc public var qaFrequentlyClick:Bool = false
    
    @objc public let keyboardToolHegiht:CGFloat = 70
    @objc public let superView = UIView()

    //初始化完成
    @objc public var isShow:Bool = false
    var TF_navigationBarHidden:Bool = true
    @objc public let liveBackgroundImageV = UIImageView()

    //快捷答题
    @objc public var _answerCard: TF_AnswerCardView?
    @objc public var answerCard: TF_AnswerCardView?
    {
            set {
                _answerCard = newValue
           }
           get {
                if _answerCard == nil
               {
                    _answerCard = TF_AnswerCardView()
                    _answerCard!.frame = CGRect(x: (self.superView.frame.size.width-325)/2.0, y: (self.superView.frame.size.height-200)/2.0, width: 325, height: 200)

                    _answerCard!.backgroundColor = UIColor.white
                   //灰色阴影
                    _answerCard!.layer.shadowOffset = CGSize(width: 1, height: 1)
                    _answerCard!.layer.shadowOpacity = 0.3
                    _answerCard!.layer.shadowColor = UIColor.lightGray.cgColor

                    _answerCard!.fastPaperDetailsSelectBlock = { [weak self] (subjectId,answerList,access_key,msg) in
                        guard let `self` = self else { return }
                        let model = TFFillExaminationAnswersParam()
                           model.subjectId = subjectId
                           model.answerList = answerList
                           model.access_key = access_key as String
                           model.type = TFExaminationTypeQuickAnswer

                        self.talkfunSDK.fillExaminationAnswers(model){[weak self] (code, error) in
                            guard let `self` = self else { return }

                           if (code == 0)
                            {
                               self.answerCardSubmitSuccessful()
                           }
                            else {
                                self.TF_toast(error!.msg )

                           }

                          }

                    }
                    _answerCard!.closeBlock = {[weak self] in
                        guard let `self` = self else { return }
                        self.removeAnserCard()

                    }
                    _answerCard!.endBlock = {[weak self] in
                        guard let `self` = self else { return }
                        self.endAnswerCardView()

                    }

          }
               return _answerCard
        }

    }
    //跳转到了课件显示
    var pushCourseDownDetailController:Bool = false
    //课件下载
    let courseDownView = TF_CourseDownLoadView()
  
    //推送的广告
     @objc public let popupPutView = TF_PopupPutView()
     //课件模式
     @objc public var courseLive = TFCourseModeLive()
     //主讲模式
     @objc public var keynoteLive = TFKeyNoteModeLive()
     //画廊模式
     @objc public var galleryLive = TFGalleryModeLive()
     /**抽奖开始*/
     @objc var _lotteryVC: TFLotteryViewController?
     @objc var lotteryVC: TFLotteryViewController? {
          set {
              _lotteryVC = newValue
         }
         get {
              if _lotteryVC == nil {
                  _lotteryVC = TFLotteryViewController()
                  _lotteryVC!.view.frame = self.superView.frame
                  _lotteryVC!.delegate = self
                  _lotteryVC!.deleteBtn.addTarget(self, action:#selector(self.deleteBtnClicked), for: .touchUpInside)

             }
            return _lotteryVC
        }
     }
     /**显示中奖人*/
     private var _myLotteryVC: TFMyLotteryViewController?
     private var myLotteryVC: TFMyLotteryViewController?
     {
         set {
             _myLotteryVC = newValue
        }
        get {
             if _myLotteryVC == nil {
                 _myLotteryVC = TFMyLotteryViewController()
                 _myLotteryVC!.view.frame = self.superView.frame
                 _myLotteryVC!.delegate = self
            }
           return _myLotteryVC
       }
     }
      /**中奖人列表*/
     private var _listLotteryVC: TFLotteryWinnerListViewController?
     private var listLotteryVC: TFLotteryWinnerListViewController?
         {
             set {
                 _listLotteryVC = newValue
            }
            get {
                 if _listLotteryVC == nil {
                     _listLotteryVC = TFLotteryWinnerListViewController()
                     _listLotteryVC!.view.frame = self.superView.frame
                     _listLotteryVC!.closeBtn.addTarget(self, action: #selector(self.closelistLotterVC), for: .touchUpInside)
                }
               return _listLotteryVC
           }
         }
    
     @objc public func deleteBtnClicked()
     {
         UIView.animate(withDuration: 0.25, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
             self.lotteryVC!.view.alpha = 0.0
         } completion: { Bool in
             self.lotteryVC!.view.removeFromSuperview()
             self.lotteryVC = nil
         }
     }
     //    #pragma mark 抽奖开始
    @objc public func onLotteryStart(_ result: TFLotteryStart) {
             //删除中奖人
             self.myLotteryVC!.view.removeFromSuperview()
             self.myLotteryVC = nil
             //删除中奖人列表
             self.listLotteryVC!.view.removeFromSuperview()
             self.listLotteryVC = nil
             
             self.view.endEditing(true)

             self.lotteryVC!.view.alpha = 1.0
             self.view.addSubview(self.lotteryVC!.view)
            
             self.lotteryVC!.lotteryStartUI()
    }
     
     //TODO: TFLotteryViewControllerDelegate- 转盘结束回调结果
     @objc func updateLotterView(winner:Bool,pub:Bool)
     {
         //删除抽奖开始
        self.lotteryVC!.view.removeFromSuperview()
        self.lotteryVC = nil
         self.view.addSubview(self.myLotteryVC!.view)
         if (winner) {
             self.myLotteryVC!.createwinnerView()
         } else {
             self.myLotteryVC!.createNOwinnerView()
         }
         if (self.prize_name.count > 0) {
             self.myLotteryVC!.winnerLab.text = self.prize_name
             self.myLotteryVC!.winnerIMg.isHidden = false
             self.myLotteryVC!.nowinnerIMg.isHidden = false
         } else {
             self.myLotteryVC!.winnerIMg.isHidden = true
             self.myLotteryVC!.nowinnerIMg.isHidden = true
         }
         self.myLotteryVC!.winnerBtn.isHidden = !pub
         self.myLotteryVC!.nowinnerBtn.isHidden = !pub
     }
     ///TODO:  TFMyLotteryViewControllerDelegate 点击了查询中奖列表
     @objc  func getlottoryList() {
         //删除中奖人
         self.myLotteryVC!.view.removeFromSuperview()
         self.myLotteryVC = nil
         //删除抽奖开始
         self.lotteryVC!.view.removeFromSuperview()
         self.lotteryVC = nil
         
         self.view.addSubview(self.listLotteryVC!.view)
         self.listLotteryVC!.tableview.reloadData()

     }
 //    //关闭中奖列表
     @objc func closelistLotterVC()
     {
         UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
             self.listLotteryVC!.view.alpha = 0.0
         } completion: { Bool in
             
             self.listLotteryVC!.view.removeFromSuperview()
             self.listLotteryVC = nil
             
             self.myLotteryVC!.view.removeFromSuperview()
             self.myLotteryVC = nil
             
         }
     }

     // #pragma mark 抽奖结束
     @objc public func onLotteryStop(_ result: TFLotteryStop) {
          //删除抽奖中的动画
          self.lotteryVC!.view.removeFromSuperview()
          self.lotteryVC = nil;
          
          self.listLotteryVC!.listData.removeAllObjects()
          self.view.endEditing(true)
          
          ///**奖品名称*/
         self.prize_name = result.prize_name as String
          //中奖人是否有自己
          var  isMe:Bool = false
          for i in 0..<result.winnerList.count {
              let dict = result.winnerList[i] as! TFLotteryWinner

              if (dict.isMe) {
                  isMe = true
                  break;
              }
          }
       
          //聊天有中奖信息
          if(isMe||result.pub)
          {
              var nickname:NSString = ""
              
              self.listLotteryVC!.listData.addObjects(from: result.winnerList as! [Any])

              for i in 0..<result.winnerList.count {

                  let nameDict = result.winnerList[i] as! TFLotteryWinner
                  var inx:NSString = "";
                  if ( i < 10) {
                      inx  = (inx as String) + "0" as NSString
                  }
                  inx = (inx as String) + (NSString.init(format: "%i.", i+1) as String) as NSString

                  inx = "  " + (inx as String) as NSString
                  
                  let name:NSString = nameDict.nickname as NSString
                  
                  nickname = (nickname as String) + (inx as String) + (name as String) as NSString
              }

          }
          self.lotteryVC!.view.alpha = 1.0
          self.view.addSubview(self.lotteryVC!.view)
          ///是否中奖
          if (isMe) {
              self.lotteryVC!.iswinner = true
          } else {
              self.lotteryVC!.iswinner = false
          }
          //是否公布
          if (result.pub) {
              self.lotteryVC!.ispub = true
          } else {
              self.lotteryVC!.ispub = false
          }
          self.lotteryVC!.lotteryStopUI()
       
      }
     
     @objc func setButtonToolsClick()
      {
          self.isShowSetButtonToolsArea(true)

          let isOpenVideo = TalkfunSettingToolsManager.shared().getToolsSwitchVideo(self.talkfunSDK.xid)

          self.setButtonView.hiddenBtn(isOpenVideo)


          let lab = self.setButtonView.nameLabArr[1] as! UILabel
          let setSwicth = self.setButtonView.swicthArr[1] as! UISwitch
              setSwicth.isOn = TalkfunSettingToolsManager.shared().getToolsSwitchCamera(self.talkfunSDK.xid)

          let str = "前置/后置"
          let string = NSMutableAttributedString.getAttributed(string: str, font: UIFont.PingFang(size: 17), foregroundColor: UIColor(red: 114/255.0, green: 121/255.0, blue: 132/255.0, alpha: 1))


          let attributes1 = [NSMutableAttributedString.Key.backgroundColor:UIColor.clear,          NSMutableAttributedString.Key.font:UIFont.PingFang(size: 17),NSMutableAttributedString.Key.foregroundColor: UIColor(red: 114/255.0, green: 121/255.0, blue: 132/255.0, alpha: 1)]

          let attributes2 = [NSMutableAttributedString.Key.backgroundColor:UIColor.clear,          NSMutableAttributedString.Key.font:UIFont.PingFang(size: 17),NSMutableAttributedString.Key.foregroundColor: UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)]
          if (setSwicth.isOn) {

              string.addAttributes(attributes1, range: NSRange(location: 0, length: 2))
              string.addAttributes(attributes2, range: NSRange(location: 2, length: 3))

          } else {
              string.addAttributes(attributes2, range: NSRange(location: 0, length: 2))


              string.addAttributes(attributes1, range: NSRange(location: 2, length: 3))

          }
          lab.attributedText = string
      }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.TF_isStatusBarHidden = UIApplication.shared.isStatusBarHidden
        UIApplication.shared.isStatusBarHidden = true

        
        if self.navigationController != nil {
            self.TF_navigationBarHidden = self.navigationController!.isNavigationBarHidden
            self.navigationController!.isNavigationBarHidden = true
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled =  false
        }
        self.liveBackgroundImageV.image = UIImage(named: "HTLive.bundle/live_back")
        self.liveBackgroundImageV.contentMode = .scaleAspectFill
//        self.addSubview(self.liveBackgroundImageV)
        
        self.deviceOrientationChange()
        self.superView.backgroundColor = UIColor(red: 33/255.0, green: 38/255.0, blue: 46/255.0, alpha: 1)
        
        let superViewH = self.getCalculateViewFrame(self.isOrientationLandscape).height
        let superViewX = self.getSafetyZone()
        let superViewW = self.getCalculateViewFrame(self.isOrientationLandscape).width-superViewX-superViewX
        self.superView.frame = CGRect(x: superViewX, y: 0, width: superViewW, height: superViewH)
        self.view.addSubview(self.superView)
        self.superView.addSubview(self.liveBackgroundImageV)
        self.liveBackgroundImageV.frame = CGRect(x: 0, y: 0, width: superViewW, height: superViewH)

        self.superView.clipsToBounds = true
        
        self.scoreView.frame = self.superView.bounds
        
        self.barrageRender.bulletSwitch = false
        self.barrageRender.isUserInteractionEnabled = false
        self.barrageRender.frame = self.superView.bounds
        self.view.addSubview(self.barrageRender)
        
        //TODO:实时的推送广告
        self.addpopupPutView()
        //TODO:奖励
        self.addAwardView()
        //TODO:签到
        self.addSignInViewUI()
        //添加键盘
        self.addKeyboardArea()
        //线路选择
        self.addLineUI()
        //课件下载
        self.initCoursedownView()

        
        //TODO:监听手机方向
//        NotificationCenter.default.addObserver(self, selector: #selector(self.deviceOrientationChange), name: Notification.Name(UIDevice.orientationDidChangeNotification.rawValue), object: nil)
        
        //TODO: SDK发生错误状态
        NotificationCenter.default.addObserver(self, selector: #selector(SDKError(notification:)), name: Notification.Name("TalkfunErrorNotification"), object: nil)
    }
    
    @objc func SDKError(notification:Notification) {
        let userInfo:[String:Any] = notification.userInfo as! [String:Any]
        
        self.promptTool.loading.isHidden = true

        if  ((userInfo["code"] ) != nil)
           {
               let msg:String = userInfo["msg"] as! String
               let code = userInfo["code"] as! String

                   if (code == "10035") {
                      self.promptTool.backgroundImage.isHidden = false
                      self.promptTool.backgroundImage.imageView.isHidden = false
                      self.promptTool.backgroundImage.label.isHidden = false
                      
                      self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/fullLive")
                       
                       self.promptTool.backgroundImage.label.text = "直播人数已满"


                   return
                       //TalkfunErrorAuthenticationFail   TalkfunErrorKick
                   }else if (code == "10010" || code == "10034") {
                     self.promptTool.backgroundImage.imageView.isHidden = false
                     self.promptTool.backgroundImage.label.isHidden = false
                       
                     self.promptTool.backgroundImage.imageView.image = UIImage.init(named: "HTLive.bundle/failLive")
                      
                       self.promptTool.backgroundImage.label.text =  msg

                       if (code == "10034") {
                       
                           self.TF_alertController("直播加载失败")
                     
                       }
                    return
                       //200001  TalkfunErrorNetworkDisconnect
                   }else if ( code == "200001") {

                       return;
                   }

            self.TF_alertController(msg)
           }
    }




   @objc func getSafetyZone()->CGFloat
    {
        var SafetyZone:CGFloat = 0

        if (self.isNotchScreen) {
              SafetyZone = 32
          }
       return SafetyZone
    }
    
    //快速答题卡倒计时结束
  @objc func endAnswerCardView()
    {
        self.answerCard?.frame = CGRect(x: (self.superView.frame.size.width-125)/2, y: (self.superView.frame.size.height-44)/2, width: 125, height: 44)

        self.answerCard!.countdownEndView.isHidden = false
        self.answerCard!.answerView.isHidden = true
        self.answerCard!.answerSuccessView.isHidden = true
        self.answerCard!.startAnswerCardSuccessTimers()

    }
    @objc func removeAnserCard()
     {
         self.answerCard!.removeFromSuperview()
         self.answerCard = nil
     }
    
    @objc func answerCardSubmitSuccessful()
     {
         self.answerCard!.frame = CGRect(x: (self.superView.frame.width-150)/2.0, y: (self.superView.frame.height-150)/2.0, width: 150, height: 150)
         self.answerCard!.answerView.isHidden = true
         self.answerCard!.answerSuccessView.isHidden = false
         self.answerCard!.countdownEndView.isHidden = true
         self.answerCard?.startAnswerCardSuccessTimers()

     }
    
   @objc func isShowTopViewAndBottomView(_ show:Bool)
    {
        UIView.animate(withDuration: 0.5) {
            if (show) {
                self.navigationBar.topView.frame = CGRect(x: self.navigationBar.topView.frame.origin.x, y: 0, width: self.navigationBar.topView.frame.size.width, height: self.navigationBar.topView.frame.size.height)


                  self.navigationBar.bottomView.frame = CGRect(x: self.navigationBar.bottomView.frame.origin.x, y: self.superView.frame.size.height-self.navigationBar.bottomView.frame.size.height, width: self.navigationBar.bottomView.frame.size.width, height: self.navigationBar.bottomView.frame.size.height)


           }else{
              self.navigationBar.topView.frame = CGRect(x: self.navigationBar.topView.frame.origin.x, y: -self.navigationBar.topView.frame.size.height, width: self.navigationBar.topView.frame.size.width, height: self.navigationBar.topView.frame.size.height)

             self.navigationBar.bottomView.frame = CGRect(x: self.navigationBar.bottomView.frame.origin.x, y: self.superView.frame.size.height, width: self.navigationBar.bottomView.frame.size.width, height: self.navigationBar.bottomView.frame.size.height)
           }
        }

    }
    // #pragma mark 投票列表出现
    @objc func questionButtonClick()
    {
        self.isShowTopViewAndBottomView(false)
        self.showChatArea(false)
        if (self.drawPower && self.talkfunSDK.liveStatus == TalkfunLiveStatusStart) {
            self.courseLive.drawing.whiteboardTools.isHidden = false
        } else {
            self.courseLive.drawing.whiteboardTools.isHidden = true
        }
        self.isShowVotingArea(true)

        self.courseLive.drawing.podiumConfiguration.vote.clearRedDot()
        self.talkfunSDK.getVotingList {[weak self] code, list, error in
            guard let `self` = self else { return }
            if (code == 0 ) {
                self.votingArea.allVotes(list!)
            }else{
                self.TF_toast(error!.msg)
            }

        }

    }
    //跳转课件下载
    func checkCourseDetail(_ model:TFdoc)
    {
        self.pushCourseDownDetailController = true
        let  vc = TFdocumentPreviewController()
        vc.urlStr = model.url
        vc.localPath = model.localPath
        vc.hidesBottomBarWhenPushed = true
        
        vc.fixedDirection = true
        if self.navigationController != nil {
           self.navigationController?.pushViewController(vc, animated: true)
        }else
        {
            self.present(vc, animated: true)
        }
    }
    
    // #pragma mark -- 课件下载
   @objc func initCoursedownView()
     {
         //课件下载
         self.courseDownView.frame = self.superView.bounds
         self.courseDownView.backgroundColor = UIColor.white
         self.courseDownView.type = .large
         self.courseDownView.downLoadRoot.delegate = self
         self.view.addSubview(self.courseDownView)
     }

    @objc func addpopupPutView()
    {
        //TODO:实时的推送广告
        self.popupPutView.mNavigationbarHeight = 0
        self.popupPutView.frame = self.superView.bounds
        self.superView.addSubview(self.popupPutView)
        
    }
    //获取下载列表数据
    @objc func courseDownBtnClick()
    {
        // MARK: - 获取下载列表数据
        let param = TFdocParam()
        param.page = 1
        param.accessToken = self.access_token
        self.courseDownView.downLoadRoot.getCourseDownData(param)
        
        self.courseDownView.showCourseDownLoad(true)
    }
    
     @objc func submitClick()
      {
          self.view.endEditing(true)
       
          if (self.scoreView.dict.count>0) {
              //留言见容
              if (self.scoreView.textView.text.count>0) {
                  
                  self.scoreView.dict.setObject(self.scoreView.textView.text, forKey: "msg" as NSCopying)
                  
             
              }
              //提交评价
              self.talkfunSDK.submitARating(self.scoreView.dict as! [AnyHashable : Any]) {[weak self] (code, error) in
         
                  guard let `self` = self else { return }
               
                  if (code == 0) {
                      self.scoreView.isSuccess(true)
                  
                  }else if (code == -1) {
                      //你已经评过分了哦。
                      self.scoreView.isSuccess(true)

                  }else{
                      self.scoreView.isSuccess(false)

                  }


              }
          }

      }
    @objc func loadChat(_ obj:TF1to16LiveChatData)
    {
        self.imageManage.loadImage(with: URL.init(string: obj.avatar as String), options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

        } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
            guard let `self` = self else {
                return
            }
            self.loadData(obj.msg, withImage: image!)

        }
    }
     
     @objc func loadImage(_ msg:String, avatar:String)
     {
         self.imageManage.loadImage(with: URL.init(string: avatar as String), options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

         } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
             guard let `self` = self else {
                 return
             }
             self.loadData(msg, withImage: image!)

         }
     }
    
    func loadData(_ content:String,withImage:UIImage)
    {
        let backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)

        //权限打开
        if self.barrageRender.bulletSwitch {
            self.barrageRender.initAvatar(withImage, content: content, ontOfSize: 16, textColor: UIColor.white, backgroundColor: backgroundColor)
        }
       

    }

   @objc func isShowVotingArea(_ show:Bool)
    {
        UIView.animate(withDuration: 0.5) {
                if (show) {
                 self.votingArea.frame = CGRect(x: self.superView.frame.size.width - self.chatArea.frame.size.width, y: self.chatArea.frame.origin.y, width: self.chatArea.frame.size.width, height: self.chatArea.frame.size.height)

            }else{
                 self.votingArea.frame = CGRect(x: self.superView.frame.size.width, y: self.chatArea.frame.origin.y, width: self.chatArea.frame.size.width, height: self.chatArea.frame.size.height)

            }
        }


    }
    
   @objc func addTimer()
    {
        if self.qa_sendTimer != nil {
            self.qa_sendTimer?.invalidate()
            self.qa_sendTimer = nil
        }
        if self.chat_sendTimer != nil {
            self.chat_sendTimer?.invalidate()
            self.chat_sendTimer = nil
        }
        let timerss = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(sendtimerAction), userInfo: nil, repeats: true)
        if (self.keyboardTool.qskQuestions.isHidden==false) {
            self.qa_sendTimer = timerss
        } else {
            self.chat_sendTimer = timerss
        }
        timerss.fire()
        RunLoop.main.add(timerss , forMode: RunLoop.Mode.default)

    }
    @objc func sendtimerAction()
    {
        if (self.keyboardTool.qskQuestions.isHidden==false) {
            if (self.qa_t == 0) {
                if self.qa_sendTimer != nil {
                    self.qa_sendTimer?.invalidate()
                    self.qa_sendTimer = nil
                }
                self.qa_t = 0;
            }
            self.qa_t =  self.qa_t - 1
        } else{
            if (self.chat_t == 0) {
                if self.chat_sendTimer != nil {
                    self.chat_sendTimer?.invalidate()
                    self.chat_sendTimer = nil
                }
                self.chat_t = 0;
            }
            self.chat_t =  self.chat_t - 1

        }

    }
    //TODO:弹窗内容
    @objc func showContent(_ content:String)
    {
        let alert = self.showContent(content, Message: "", Cancel: "", Sure: "确定")

        alert.sureBtn.addTarget(self, action: #selector(sureBtn2), for: .touchUpInside)
    }
    @objc func sureBtn2(_ btn:UIButton)
    {
        if (btn.superview != nil) {
            btn.superview?.removeFromSuperview()
        }
    }
   @objc func showContent(_ content:String,Message:String,Cancel:String,Sure:String)->TFAlertView
    {
        let alert = TFAlertView()
        alert.title(content, meaasge: Message, sureTitle: Sure, cancleTitle: Cancel)
        alert.showAlertView(self.superView)
        return alert;
    }
    //4.聊天区域
    @objc func addChatArea()
     {
         let ChatAreaY:CGFloat = 0.0
         let ChatAreaHeight:CGFloat = self.superView.frame.size.height
         let ChatAreaW:CGFloat =  335
         let ChatAreaX =  self.superView.frame.size.width
         self.chatArea.frame = CGRect(x: ChatAreaX, y: ChatAreaY, width: ChatAreaW, height: ChatAreaHeight)
         self.superView.addSubview(self.chatArea)

    }
    @objc func getNumber(_ obj:NSObject)->String
    {
        var UsersXid:String = "0"
        
        if(obj is NSNumber){

            let num:NSNumber = obj as!NSNumber
           
            
            UsersXid = NSString.init(format: "%i", num) as String
        }

        return UsersXid;
    }
    func addChatData(_ chatData:TFChatData)
    {
        if (chatData.imageURL.count > 0 ) {
            self.imageManage.loadImage(with: URL.init(string: chatData.imageURL as String), options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

            } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
                guard let `self` = self else {
                    return
                }
                let model = self.getLivingChatData(chatData)
                model.image = image
                self.addModel(model)

            }

        }else{
            let model = self.getLivingChatData(chatData)
            self.addModel(model)

        }

    }

    //  #pragma mark 投票详情
      func getVoteDetail(_ vid:String)
     {
         self.talkfunSDK.getVotingDetails(vid) { [weak self] (code, model, error) in
             guard let `self` = self else { return }

             if (code==0) {
                 self.votingArea.tableView.isHidden = true
                 self.votingArea.voteDetail.updateVoteDetail(model!)
             }else{
                 self.TF_toast(error!.msg)

             }
         }

      }
    // #pragma mark  聊天发送出去
   @objc func longSendButtonClick()
     {
         if (self.keyboardTool.qskQuestions.isHidden==false) {
             
             
           if (self.keyboardTool.qskQuestions.text.count==0) {

               self.superView.endEditing(true)
               self.TF_toast("请输入要提问的内容！")

                  return;
              }

             if (self.qaFrequentlyClick == true) {
                 let chatStr = String.init(format: "您发言太快,请%d秒后重试", self.qa_t)
                 self.superView.endEditing(true)
                 self.TF_toast(chatStr)

                 return;
             }

             self.qa_t = self.talkfunSDK.roomInfo.mod_text_live.config.qa.interval
             self.addTimer()
             self.qaFrequentlyClick = true
             
             let int1 = CGFloat(self.qa_t)
             
             DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+int1) {
                 self.qaFrequentlyClick = false
                    }
    
             self.talkfunSDK.enterAskQuestions(self.keyboardTool.qskQuestions.text) {[weak self] code, model, error in
                 guard let `self` = self else { return }
                 self.keyboardTool.qskQuestions.text = ""
                 
                 self.qskQuestionsView.addQskQuestionsDict(model!)
                 
             }


              self.keyboardTool.qskQuestions.text = ""
             self.superView.endEditing(true)
          

             self.keyboardTool.qskQuestions.text = ""
         }else{
             self.keyboardTool.frame = CGRect(x: 0, y: self.superView.frame.size.height, width: self.superView.frame.size.width, height: self.keyboardToolHegiht)
            
             //隐藏键盘
             self.superView.endEditing(true)

             if (self.chatFrequentlyClick == true) {
                
                 let chatStr =  String.init(format: "您发言太快,请%d秒后重试", self.chat_t)
                 self.TF_toast(chatStr)
               
                 return
             }
             self.chat_t = self.talkfunSDK.roomInfo.mod_text_live.config.chat.interval
             self.addTimer()
           
             self.chatFrequentlyClick = true

             let int1 = CGFloat(self.chat_t)
             DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+int1) {
                 self.chatFrequentlyClick = false;
                    }
         

             if(self.keyboardTool.inputField.text.count>0){
                 self.emit(self.keyboardTool.inputField.text)
          
                 //初始化输入栏
                 self.keyboardTool.inputField.text = ""
                 self.navigationBar.inputField.text = ""

             }
         }
     }
    func emit(_ msg:String)
    {

        if (self.talkfunSDK.chatBeforeClass == false&&self.talkfunSDK.liveStatus == TalkfunLiveStatusWait) {

            self.superView.endEditing(true)
            self.TF_toast("课前禁止聊天互动")

               return;
           }
           if (self.talkfunSDK.chatAfterClass==false&&self.talkfunSDK.liveStatus == TalkfunLiveStatusStop) {
               self.superView.endEditing(true)
               self.TF_toast("课后禁止聊天互动")

               return;
           }
        
        self.talkfunSDK.sendChat(msg) {[weak self] code, model, error in
            guard let `self` = self else { return }

            if (code == 0 ) {
                self.addModel(self.getLivingChatData(model!))
           
            }else{
                self.TF_toast(error!.msg)
            }

        }
    }
    func addModel(_ model:TF1to16LiveChatData)
    {
        //显示聊天
        self.chatArea.setChat(model)
        //弹幕
        if (model.imageURL.count==0) {
            //弹幕
            self.loadChat(model)
        }
    }
     //textViewShouldBeginEditing
    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
         
         if (textView == self.keyboardTool.inputField) {
             self.keyboardTool.setfCommonLanguageTitle()
         }
        return true
     }
    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        if text == "\n" {
        //回车
            self.longSendButtonClick()


                 return false
           }

        return true
    }
    /*
     监听键盘的即将显示
     */
    @objc func keyboardWillShow(noti:NSNotification)
    {
        if self.scoreView.textView.isFirstResponder {
            return
        }
        let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
        
        let keyboardFrameEnd:NSValue = keyboardInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
        
        let keyboardFrameEndRect:CGRect = keyboardFrameEnd.cgRectValue

        let height = keyboardFrameEndRect.size.height

        self.keyboardTool.frame = CGRect(x: 0, y: self.superView.frame.size.height - height - self.keyboardToolHegiht, width: self.superView.frame.size.width, height: self.keyboardToolHegiht)
      
        self.superView.addSubview(self.keyboardTool)

    }
    // #pragma mark-----------------------------------键盘隐藏
    @objc func keyboardWillHide()
     {
         //ipad的文字同步
          self.navigationBar.inputField.text =  self.keyboardTool.inputField.text
         if(self.keyboardTool.frame.size.height>70){
             return
         }

         self.keyboardTool.frame = CGRect(x: 0, y: self.superView.frame.size.height, width: self.superView.frame.size.width, height: self.keyboardToolHegiht)

     }
    @objc func keyboardWillHide1()
     {
       self.superView.endEditing(true)
       self.keyboardWillHide()
       self.isShowSetButtonToolsArea(false)

       self.showChatArea(false)
   
         UIView.animate(withDuration: 0.5) {
             self.keyboardTool.frame = CGRect(x: 0, y: self.superView.frame.size.height, width:  self.superView.frame.size.width, height: self.keyboardToolHegiht)

         }
       self.isShowVotingArea(false)

     }
    
    func addLineUI()
    {
        //TODO:线路
       self.other.frame = CGRect(x:self.superView.frame.size.width , y: 0, width: 115, height: self.superView.frame.size.height)
     
       self.other.backgroundColor = UIColor(red: 21/255.0, green: 34/255.0, blue: 54/255.0, alpha: 0.95)
     
       self.other.networkOperators = {[weak self] dict in
           guard let `self` = self else { return }
           self.isShowOtherArea(false)
           let selectedSegmentIndex = dict["selectedSegmentIndex"] as! NSString
           
       
           self.talkfunSDK.setNetwork("auto", selectedSegmentIndex: Int(selectedSegmentIndex.intValue)) {[weak self] code, error in
               guard let `self` = self else { return }
               if(code==0)
               {
                   self.TF_toast( String.init(format: "已切换到线路%ld", Int(selectedSegmentIndex.intValue)) )
               }else{
                   self.TF_toast(error!.msg)
               }
              
           }
         
    }


   }
  @objc func isShowOtherArea(_ isShow:Bool)
    {
        self.superView.addSubview(self.other)
        UIView.animate(withDuration: 0.6) {
            if (isShow) {
                   self.other.frame = CGRect(x: self.superView.frame.size.width-115, y: 0, width: 115, height: self.superView.frame.size.height)
             }else{
                 self.other.frame = CGRect(x: self.superView.frame.size.width, y: 0, width: 115, height: self.superView.frame.size.height)

             }
        }
    }
    
    @objc func isShowSetButtonToolsArea(_ isShow:Bool)
    {
        UIView.animate(withDuration: 0.6) {
            if (isShow) {
                   self.setButtonView.frame = CGRect(x: self.superView.frame.size.width-220, y: 0, width: 220, height: self.superView.frame.size.height)


             }else{
                    self.setButtonView.frame = CGRect(x: self.superView.frame.size.width, y: 0, width: 220, height: self.superView.frame.size.height)

             }
        }

    }
    @objc func showChatArea(_ isShow:Bool)
    {
        if self.navigationBar.isFullButton.isSelected{
            return
        }
        UIView.animate(withDuration: 0.5) {
            let  ChatAreaY:CGFloat = 0.0
            let  ChatAreaHeight:CGFloat = self.superView.frame.size.height
            let  ChatAreaW:CGFloat = 335
            let  ChatAreaX:CGFloat = self.superView.frame.size.width
          if (isShow) {
              self.chatArea.frame = CGRect(x: self.superView.frame.size.width-ChatAreaW, y: ChatAreaY, width: ChatAreaW, height: ChatAreaHeight)

          }else{
              self.chatArea.frame = CGRect(x: ChatAreaX, y: ChatAreaY, width: ChatAreaW, height: ChatAreaHeight)

          }
        }


    }
    func getLivingChatData(_ dict:TFChatData)->TF1to16LiveChatData
    {
        let model = TF1to16LiveChatData()
        model.chat = dict.chat
        model.gender = dict.gender
        model.uid = dict.uid
        model.a = dict.a
        model.time = dict.time
        model.gid = dict.gid
        model.avatar = dict.avatar
        model.isMe = dict.isMe
        model.role = dict.role
        model.term = dict.term
        model.nickname = dict.nickname
        model.msg = dict.msg
        model.xid = dict.xid
        model.attr = dict.attr
        model.replyList = dict.replyList
        model.imageURL = dict.imageURL
        model.money = dict.money
        model.uuid = dict.uuid
        model.isChat = true
        return model
    }
    
   @objc func getLiveDuration(_ obj:TFLiveDuration)->String
    {
        var hour = ""
        var minute = ""
        var second = ""

        //前面加0
        if ( obj.hour < 10 ) {

            hour =  "0" + String.init(format: "%li:", obj.hour)
        }else{
            hour = String.init(format: "%li:", obj.hour)
        }
        //前面加0
        if ( obj.minute < 10 ) {

            minute =  "0" + String.init(format: "%li:", obj.minute)
        }else{
            minute =  String.init(format: "%li:", obj.minute)
        }
        //前面加0
        if ( obj.second < 10 ) {

            second =  "0" + String.init(format: "%li", obj.second)
        }else{
            second =  String.init(format: "%li", obj.second)
        }

        let dateContent = hour + minute + second

        return dateContent
    }
    //代理方法
   @objc public func marqueeClick() {

       if (self.marquee.url.count>0) {
           
        TalkfunSharedTools.openUrl(str: self.marquee.url as NSString)

        }
    }
    
    //全屏
     @objc  func double_tap_to_full_screenUI(_ model:TalkfunRtcModel)
     {
         if (self.talkfunSDK.liveStatus != TalkfunLiveStatusStart) {
             return;
         }

         self.fullView.frame = UIScreen.main.bounds
         self.fullView.isHidden = false
        
         self.fullView.model = model

         if (model.video == .closeForZHUBO || model.video == .closeForUser) {
                 self.fullView.view.isHidden = false
         } else {

                     model.view.frame = self.fullView.bounds
                     self.fullView.insertSubview(model.view, at: 0)

                     self.fullView.view.isHidden = true

             }

             model.isFull = true
         self.view.addSubview(self.fullView)

     }
    //#pragma mark 自己的大奖励
    func addAwardView()
    {
        self.awardView.isUserInteractionEnabled = false
        self.superView.addSubview(self.awardView )

        self.awardView.frame = self.superView.bounds
        self.awardView.backgroundColor = UIColor.clear
    }
     @objc func addSignInViewUI()
     {
         //TODO:签到View
         self.signInView.delegate = self
         self.signInView.frame = self.superView.bounds
         self.signInView.view.frame = CGRect(x: 0, y: self.signInView.frame.size.height, width: self.signInView.frame.size.width, height: 312)
         self.superView.addSubview(self.signInView)
         //TODO:确定签到事件
         self.signInView.round.addTarget(self, action: #selector(self.SignInClick), for: .touchUpInside)

     }
    @objc func SignInClick()
    {
        
        //点名签到
        self.talkfunSDK.sign(in: self.signInView.result!.signId) {[weak self] code, error in
            guard let `self` = self else { return }

            //签到成功
            if (code==0) {
              
//                self.liveGoldTo(userID: self.userID)
                let parameters: [String: Any] = ["userId: ": "1790624317088862208", "type": 1]
                NetWorkTools.shareInstance.request(requestType: .POST, url: "https://yuanfangapi.mourinet.com/app/live/addCoinByLive", parameters: parameters) { data in
                    self.TF_toast("签到成功")
                    self.signInView.roundClickUI()
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2) {
                        self.signInView.onSignEndUI(result: TFSignEnd())
                        }

                } failure: { error in
                    
                };
              
            }else{
                self.TF_toast("签到失败")
            
            }
        }
    }
   public func liveGoldTo(userID: String){
        // 创建URL对象
        guard let url = URL(string: "https://yuanfangapi.mourinet.com/app/live/addCoinByLive") else {
            fatalError("Invalid URL")
        }
        // 创建URLRequest对象
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
         
        // 准备参数
        let parameters: [String: Any] = ["userId: ": userID, "type": 1]
         
        // 将参数转换为JSON数据
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
            request.httpBody = jsonData
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        } catch {
            print("Error creating JSON: \(error)")
        }
         
        // 创建URLSession数据任务并启动
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            // 确保没有错误发生
            if let error = error {
                print("Error: \(error)")
                return
            }
            
            // 确保我们有数据返回
            guard let data = data else {
                print("No data in response")
                return
            }
            
            // 对返回的数据进行处理（例如解析JSON）
            do {
                let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
                print(jsonObject)
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
         
        // 启动任务
        task.resume()
    }
    //
    @objc func flowersClick()

     {
         self.view.endEditing(true)
         
         //送花
         self.talkfunSDK.sendFlower {[weak self] code, model, flower_left_time in
             guard let `self` = self else { return }
             self.keyboardTool.flower.drawRedDotWidthNumber("0")
           if (code==0) {

               self.chatArea.setFlowersDict(model!)
                 }else{

                     self.keyboardTool.flower.prompt(NSString.init(format: "%i", flower_left_time) as String)


             }
             
         }
    
     }
    //键盘处理
    func addKeyboardArea()
    {
        //键盘工具
        self.keyboardTool.inputField.delegate = self
        self.keyboardTool.inputField.returnKeyType = .send//变为发送按钮
        
        self.keyboardTool.backgroundColor = UIColor(red: 255/255.0 , green: 255/255.0 , blue: 255/255.0 , alpha: 1)
        self.keyboardTool.frame = CGRect(x: 0, y: self.superView.frame.size.height, width: self.superView.frame.size.width, height: self.keyboardToolHegiht)
    
        self.superView.addSubview(self.keyboardTool)
        
        self.keyboardTool.flower.addTarget(self, action: #selector(flowersClick), for: .touchUpInside)
     
        
        //常用语===>
//        WeakSelf
        self.keyboardTool.commonPhrasesView.commonLanguageBlock = {[weak self] str in
            guard let `self` = self else { return }
            self.emit(str)
            //调用sdk发送聊天
            
            //隐藏键盘
            self.keyboardWillHide1()
         
        }
        self.keyboardTool.longSendButton.addTarget(self, action: #selector(self.longSendButtonClick), for: .touchUpInside)

        //TODO:监听键盘的即将显示  通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide1), name: Notification.Name("keyboardWillHide"), object: nil)
        
        //TODO: SDK发生错误状态
        NotificationCenter.default.addObserver(self, selector: #selector(SDKError(notification:)), name: Notification.Name("TalkfunErrorNotification"), object: nil)

    }
     // MARK: - sdk ----------------------代理---------------------
     //   #pragma mark 已直播时长
     @objc public func onLiveDuration(_ result: TFLiveDuration) {

            if (self.talkfunSDK.roomInfo.mod_liveinfo_live.config.liveTime.enable == true) {

            if(self.navigationBar.time.isHidden){
               self.navigationBar.time.isHidden = false
  
            }
                let time = "   " + self.getLiveDuration(result)
                self.navigationBar.time.setTitle(time, for: .normal)
            } else {
                self.navigationBar.time.isHidden = true
            }
        }
     //  #pragma mark 接收滚动通知事件回调
     @objc public func onAnnounceRoll(_ result: TFAnnounceRoll) {
           self.marquee.initContent(result.content, link: result.link, duration: result.duration)
          
       }
     //   #pragma mark 公共广播
     @objc public func onBroadcast(_ result: TFBroadcast) {

         let model = TF1to16LiveChatData()
         model.time = result.time
         model.gid = result.gid
         model.msg = result.msg
         model.isBroadcast = true
         self.chatArea.setPublicBroadcasting(model)

         if (self.isShow){
           //画小红点
           if (self.chatArea.frame.origin.x == self.superView.frame.size.width) {
               self.navigationBar.chat.drawRedDot()
           }

         }

     }
     //#pragma mark 未连麦人员奖励

     @objc public func onMemberAward(_ model: TFMember) {
         let chatData = TF1to16LiveChatData()
         chatData.nickname = model.nickname
         chatData.score = model.score
         chatData.isAward = true
         
         self.chatArea.setAwardModel(chatData)

         if (model.isMe) {
             self.superView.addSubview(self.awardView)
             self.awardView.rotateView()
         }
     }
     //   #pragma mark 推送公告的事件回调
     @objc public func onAnnouncement(_ result: TFAnnouncement) {
            self.chatArea.setAnnouncement(result)
        
            //画小红点
            self.navigationBar.chat.drawRedDot()

            var msg = result.content as String
      
            if (msg.contains("[IMG]")&&msg.contains("[/IMG]")) {
                msg = msg.replacingOccurrences(of:"[IMG]" , with:"" )
                msg =  msg.replacingOccurrences(of:"[/IMG]" , with:"" )
                self.barrageRender.initWithContent("公告: "+msg, ontOfSize: 16, textColor: UIColor.white)
               
            }else{
                self.barrageRender.initAvatar(UIImage.init(named: "HTLive.bundle/popgonggao"), content: msg, ontOfSize: 15, textColor: UIColor.white, backgroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 0.6))

            }
        }

     //删除聊天
     @objc public func onChatDel(_ uuid: String) {
         self.chatArea.chatDel(uuid)

     }
     //#pragma mark  接收别人的聊天事件回调
     @objc public func onDidReceiveText(_ result: TFChatData) {

         self.addChatData(result)
         if (self.isShow){
              if (self.chatArea.frame.origin.x == self.superView.frame.size.width) {
                  self.navigationBar.chat.drawRedDot()
              }
         }
     }
     //    #pragma mark - 结束签到的事件回调
     @objc public func onSignEnd(_ result: TFSignEnd) {
         
         self.signInView.onSignEndUI(result: result)
         self.TF_toast("点名结束")
       
     }
     //    #pragma mark 接收主播发起签到的事件回调
     @objc public func onSignNew(_ result: TFSignNew) {
         self.signInView.frame = CGRect(x: (self.superView.frame.width-240)/2, y: (self.superView.frame.height-312)/2, width: 240, height: 312)
         self.superView.addSubview(self.signInView)

         self.signInView.onSignNewUI(result: result)
        
     }
     //  #pragma mark  投票删除的事件回调
     @objc public func onVoteDel(_ result: TFVoteData) {
          self.votingArea.delVote(result)
       }
     //#pragma mark 投票结束的事件回调
     @objc public func onVotePub(_ result: TFVoteData) {

      self.votingArea.votePub(result)
     }
     
     //#pragma mark 发布随堂测试时
     @objc public func onExaminationPush(_ result: TFQuestionnairePushResult) {

         if (result.type == TFExaminationTypeQuickAnswer) { //快速答题卡
             
             let params = TTFExaminationDetailParam()
             params.id = result.id
             params.type = TFExaminationTypeQuickAnswer
             
             self.talkfunSDK.getExaminationDetail(params) {[weak self] (code, result1, error) in
                 
                 guard let `self` = self else { return }
                 if (code == 0) {
                     self.view.addSubview(self.answerCard!)
                     self.answerCard?.setAnswerCard(result1)
                   
                     self.answerCard!.answerCardId = result.id
                     self.answerCard!.addTimer(result.endTime)
                 }
             }
       
         }

     }
    // #pragma mark 主播提前-结束作答随堂测试
     @objc public func onExaminationEnd(_ result: TFQuestionnaireEndResult) {
     
         //快速答题卡
         if ((self.answerCard != nil) && result.type == TFExaminationTypeQuickAnswer) {
             if (result.id == self.answerCard!.answerCardId) {
                 self.endAnswerCardView()
                 
             }
         }

     }
     //#pragma mark 投票开始的事件回调
   @objc public func onVoteNew(_ result: TFVoteData) {
         self.votingArea.voteNew(result)

       if (self.votingArea.frame.origin.x == self.superView.frame.size.width) {
         self.navigationBar.voteBtn.drawRedDot()
       }
         self.courseLive.drawing.podiumConfiguration.vote.drawRedDot()
     }
     
     // MARK: - 画板选中的----------------------代理---------------------
     //颜色选择
     @objc public func chooseColor(_ rgbColor: UIColor) {
         
         self.talkfunSDK.rtcManager.whiteboard.setLineRgbColor(rgbColor)
      
     }
     //点击了涂鸦
     @objc public func chooseGraffiti(_ tag: NSInteger) {
    
         if (tag == 0) {
               self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeStroke
         }else if (tag == 1) {
               self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeStraightLine
         }
         else if (tag == 2) {
               self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeDottedLine
         }else if (tag == 3) {
               self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeRectangle
         }else if (tag == 4) {
               self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeCircle
         }
     }
     //选择了橡皮擦
     @objc public func chooseEraser() {
   
         self.talkfunSDK.rtcManager.whiteboard.drawType =  TalkfunDrawTypeBoxDelete
     }
     //宽度选择
     @objc public func chooseWidth(_ tag: NSInteger) {
  
         if (tag==0) {
              self.talkfunSDK.rtcManager.whiteboard.lineWidth =  TalkfunDrawLineWidthSmall
         }else if (tag==1)
         {
             self.talkfunSDK.rtcManager.whiteboard.lineWidth =  TalkfunDrawLineWidthMiddle
         }else if (tag==2)
         {
               self.talkfunSDK.rtcManager.whiteboard.lineWidth =  TalkfunDrawLineWidthBig
         }else if (tag==3)
         {
               self.talkfunSDK.rtcManager.whiteboard.lineWidth =  TalkfunDrawLineWidthLarge
         }

     }
    @objc func sureBtnUI()
    {
        ///**响应被邀请上讲台2.0*/
        self.talkfunSDK.rtcManager.respondinviteRTC(TalkfunRespondinviteStatusAccept) { [weak self] (code, error) in
            
            guard let `self` = self else { return }
            if(code==0){
             self.navigationBar.ondium.onPodium(.allow)
         
            }else
            {
                self.TF_toast("上讲台失败")
            }
            
            self.alertInvite.removeFromSuperview()
            
        }
    }
    
    @objc func cancelBtnUI()
    {
        self.talkfunSDK.rtcManager.respondinviteRTC(TalkfunRespondinviteStatusReject) { [weak self]  (code, error) in
            guard let `self` = self else { return }
            self.alertInvite.removeFromSuperview()
        }
    }
     // #pragma mark 邀请上讲台
    @objc public func rtcInvite() {

         let alert = self.showContent("主播邀请你连麦", Message: "", Cancel: "拒绝", Sure: "同意")
          
        self.alertInvite = alert
        alert.sureBtn.addTarget(self, action: #selector(sureBtnUI), for: .touchUpInside)
        alert.cancelBtn.addTarget(self, action: #selector(cancelBtnUI), for: .touchUpInside)
        
      }
     // #pragma mark 被取消邀请上讲台
     @objc public func rtcInvitecancel() {
          self.alertInvite.removeFromSuperview()
          self.TF_toast("已取消邀请上讲台")
      }
    
    //TODO: 签到倒计时结束 TF_SignInDelegate
    public func signEnd() {
        
    }
    
    // #pragma mark 推送弹窗广告的事件回调
 @objc public func onPopupPut(_ result: TFPopupPut) {
         self.superView.addSubview(self.popupPutView)
         self.popupPutView.addPopupPut(result: result)
     }
    //自动换方向
    @objc func deviceOrientationChange()
    {
        self.isOrientationLandscape = true
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        
    }
    @objc func UIInterfaceOrientationPortrait()
    
    {
        self.isOrientationLandscape = false
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        
        
        UIApplication.shared.isStatusBarHidden  =  self.TF_isStatusBarHidden
        
        if self.navigationController != nil {
          
            self.navigationController!.isNavigationBarHidden = self.TF_navigationBarHidden
            self.navigationController!.interactivePopGestureRecognizer!.isEnabled = false
        }
    }
    

    // MARK: - 横竖屏支持
    
    public override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
//        if self.navigationController != nil  {
//            return [UIInterfaceOrientationMask.landscapeRight, UIInterfaceOrientationMask.portrait]
//        }else
//        {
//            if self.isOrientationLandscape {
                return UIInterfaceOrientationMask.landscapeRight
//            }
//            return  UIInterfaceOrientationMask.portrait
//        }
    }
    //#pragma mark - 旋转
    
    public var shouldAutorotateToInterfaceOrientation: Bool{
        return true
    }
    
    public override var shouldAutorotate: Bool{
        return true
    }
    ////隐藏状态栏
    public override var prefersStatusBarHidden: Bool
    {
        return true
    }
}

enum HTTPMethod : Int{
    
    case  GET = 0
    
    case  POST = 1
    
}


class NetWorkTools: AFHTTPSessionManager {
    
    //设置NetWorkTools单例对象 执行闭包
    
    static let shareInstance :NetWorkTools = {
        
        let tools = NetWorkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
        
    }()
    
}


extension NetWorkTools {
    
    func request(requestType : HTTPMethod, url : String, parameters : [String : Any]?, succeed : @escaping([String : Any]?) -> (), failure : @escaping(Error?) -> ()) {
        
        // 定义成功闭包
        
        let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in
            
            succeed(responseObj as? [String : Any])
            
        }
        
        // 定义失败的闭包
        
        let failureBlock = { (task: URLSessionDataTask?, error: Error) in
            
            failure(error)
            
        }
        
        // Post 请求
        
        if requestType == .POST {
            
            post(url, parameters: parameters, headers: [:], progress: nil, success: successBlock, failure: failureBlock)
            
        }
        
    }
}
